import { find, instantiate, Node, Prefab, resources } from "cc";

export enum DialogDef{

  UISettings = 'UISettings',

  UISikllsUpGrade = 'UISikllsUpGrade'
}

export class UIManager{

  private static _instance: UIManager = null;

  static get instance():UIManager{
    if(this._instance == null)
    {
      this._instance = new UIManager();
    }
    
    return this._instance;
  }

  
  panels:Map<string,Node> = new Map();

  uiRoot: Node = null;

  currentDiaLogPage: string = null;

  isOpenIng: boolean = false;

  openPanel(name:string, bringToTop:boolean=true)
  {
    if(this.uiRoot == null)
      this.uiRoot = find("UiRoot")

    if(this.isOpenIng) return;

    this.isOpenIng = true;

    if(this.panels.has(name))
    {
      const panel = this.panels.get(name);
      panel.active = true;
      if(bringToTop)
      {
        const len = panel.parent.children.length  - 1;
        panel.setSiblingIndex(len);
      }
      this.isOpenIng = false;
      return;
    }


    resources.load("ui/prefab/" + name, Prefab, (err:Error, data:Prefab) => {
      const panel = instantiate(data);
      this.panels.set(name, panel);
      this.uiRoot.addChild(panel);
      if(bringToTop)
      {
        const len = panel.parent.children.length  - 1;
        panel.setSiblingIndex(len);
      }
      this.isOpenIng = false;
    })
  }


  closePanel(name:string, destory:boolean = false)
  {
    if(!this.panels.has(name))
      return;

    const panel = this.panels.get(name);
    if(destory)
    {
      this.panels.delete(name);
      panel.removeFromParent();
      return;
    }
    panel.active = false;

  }

  openDialog(name:string)
  {
   for(const dialogDef in DialogDef)
   {
    if(dialogDef == name)
    {
      this.openPanel(name);
      this.currentDiaLogPage = name;
    }else{
      this.closePanel(dialogDef);
    }
   }

  }

  closeDialog(destory:boolean=false)
  {
    if(this.currentDiaLogPage != null)
    {
      this.closePanel(this.currentDiaLogPage, destory);
    }
  }
}